<template>
  <div class="h100 rightDrawerWithoutCol">
    <a-form-model
      :rules="rules"
      ref="formComp"
      :model="newServiceData"
      layout="horizontal"
      class="AsteriskAfter newEditStyle"
      style="width: 80%"
    >
      <a-form-model-item>
        <!-- 服务代码 -->
        <a-col :sm="24">
          <a-form-model-item prop="serviceCode" :label="$t('serviceCode')">
            <a-input placeholder="该值必须与车端智驾功能代码一致" :max="20" :disabled="!!recordData.id" v-model="newServiceData.serviceCode"></a-input>
            <!--<service-tem-select-->
              <!--:disabled="!!recordData.id"-->
              <!--:default-value="newServiceData.serviceCode"-->
              <!--:time="instantUpdateTime"-->
              <!--@changeoption="changeoption($event, 'serviceCode')"-->
            <!--&gt;-->
            <!--</service-tem-select>-->
          </a-form-model-item>
        </a-col>
        <!-- 服务名称 -->
        <a-col :sm="24">
          <a-form-model-item prop="serviceName" :label="$t('serviceName')">
            <a-input :placeholder="$t('pleaseInput')+$t('serviceName')" v-model="newServiceData.serviceName"></a-input>
          </a-form-model-item>
        </a-col>
        <!--选择车型代码-->
        <a-col :sm="24">
          <a-form-model-item prop="modelDtoList" :label="$t('select') + $t('modelCode')">
            <!-- searchModelList  -->
            <a-select
              placeholder="车型选择"
              mode="multiple"
              :filter-option="false"
              showSearch
              @search="getModelCodeList"
              :value="newServiceData.modelDtoList"
              @blur="getModelCodeList('')"
              @change="changeoption($event, 'modelDtoList')"
            >
              <!---->
              <a-select-option :disabled="disabledModelArr.includes(item.id)" v-for="item in modelOptions" :key="item.id" :value="item.id">
                {{ item.showName }}
              </a-select-option>
              <!-- :readonly="disabledModelArr.includes(item.code)" -->
            </a-select>
            <!--<car-model-code-select-->
              <!--:query="{ time:instantUpdateTime, selectAll: false}"-->
              <!--:has-all="false"-->
              <!--placeholder="车型选择"-->
              <!--mode="multiple"-->
              <!--@change="changeoption($event, 'serviceBelong')"-->
              <!--v-model="newServiceData.modelDtoList"-->
            <!--&gt;</car-model-code-select>-->
          </a-form-model-item>
        </a-col>
        <!-- 服务归属域 -->
        <a-col :sm="24">
          <a-form-model-item prop="serviceBelong" :label="$t('fwgsy')">
            <a style="position: absolute; right: 0; top: -38px" @click="editBelogCate('fwgsy')">{{ $t('edit') }}</a>
            <service-belong-select
              :default-value="newServiceData.serviceBelong"
              @changeoption="changeoption($event, 'serviceBelong')"
            >
            </service-belong-select>
          </a-form-model-item>
        </a-col>
        <!-- 服务分类 -->
        <a-col :sm="24">
          <a-form-model-item prop="serviceCategory" :label="$t('fwfl')">
            <a style="position: absolute; right: 0; top: -38px" @click="editBelogCate('fwfl')">{{ $t('edit') }}</a>
            <service-sale-cate-select
              :default-value="newServiceData.serviceCategory"
              @changeoption="changeoption($event, 'serviceCategory')"
            >
            </service-sale-cate-select>
          </a-form-model-item>
        </a-col>
        <!-- 服务说明 -->
        <a-col :sm="24">
          <a-form-model-item prop="serviceExplain">
            <template slot="label">
              {{ $t('serviceDescription') }}
              <a-tooltip placement="top" :getPopupContainer="$commonFun.getPopupContainer">
                <template slot="title">
                  <span>{{ $t('serviceDescriptionTip') }}</span>
                </template>
                <a-icon type="question-circle" />
              </a-tooltip>
            </template>
            <custom-text-area
              @change="changeoption($event, 'serviceExplain')"
              :val="newServiceData.serviceExplain"
              :max-len="200"
              :rows="3"
              :placeholder="$t('pleaseInput') + $t('serviceDescriptionTip').toLowerCase()"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
        <!-- 服务介绍 -->
        <a-col :sm="24">
          <a-form-model-item prop="serviceDesc">
            <template slot="label">
              {{ $t('ServiceIntroduction') }}
              <a-tooltip placement="top" :getPopupContainer="$commonFun.getPopupContainer">
                <template slot="title">
                  <span>{{ $t('serviceIntroductionTip') }}</span>
                </template>
                <a-icon type="question-circle" />
              </a-tooltip>
            </template>
            <custom-text-area
              @change="changeoption($event, 'serviceDesc')"
              :val="newServiceData.serviceDesc"
              :max-len="200"
              :rows="3"
              :placeholder="$t('pleaseInput') + $t('serviceIntroductionTip').toLowerCase()"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-form-model-item>
      <!-- 是否需学习 -->
      <!-- <a-form-model-item prop="needStudy" :label="$t('needToLearn')">
        <need-to-learn-select
          :default-value="newServiceData.needStudy"
          placeholderText="qxzsfxx"
          @changeoption="changeoption($event, 'needStudy')"
        >
        </need-to-learn-select>
      </a-form-model-item> -->
      <!-- 学习地址 -->
      <!-- <a-form-model-item v-if="newServiceData.needStudy" prop="studyUrls">
        <template slot="label">
          <span>
            {{ $t('learnUrl') }}
          </span>
        </template>
        <a-input
          v-model="newServiceData.studyUrls[0]"
          @change="checkStudy(0)"
          :placeholder="$t('请输入学习地址url')"
        ></a-input> -->
        <!--<span v-show="studyUrlErr[0] && studyUrlErr[0].error" class="has-error">-->
          <!--<span class="ant-form-explain">{{ $t('length200') }} </span>-->
        <!--</span>-->
        <!-- <div v-for="(item, index) in newServiceData.studyUrls" :key="index" class="urlItems">
          <a-input
            :key="index"
            v-model="newServiceData.studyUrls[index]"
            @change="checkStudy(index)"
            :placeholder="$t('请补充学习视频url')"
          ></a-input>

          <i v-if="index" class="iconfont icon-shanchu deleteUlr" @click="handleDelete(index)"></i>
        </div> -->
        <!-- <a-button class="newBtn" @click="addStudyUrls"> + </a-button> -->
      <!-- </a-form-model-item>  -->
      <!-- 考试地址 -->
      <!-- examUrl -->
      <!-- <a-form-model-item prop="examUrl" v-if="newServiceData.needStudy" :label="$t('examUrl')">
        <a style="position: absolute; right: 0; top: -38px" @click="editBelogCate('examUrl')">{{ $t('edit') }}</a> -->
        <!-- <a-input v-model="newServiceData.examUrl"></a-input> -->
        <!-- <service-sale-exam-select
          :default-value="newServiceData.examUrl"
          @changeoption="changeoption($event, 'examUrl')"
        ></service-sale-exam-select>
      </a-form-model-item> -->
    </a-form-model>
  </div>
</template>
<script>
import needToLearnSelect from '@/views/components/needToLearnSelect'
import ServiceBelongSelect from '@/views/components/ServiceBelongSelect'
import ServiceSaleCateSelect from '@/views/components/ServiceSaleCateSelect'
import ServiceSaleExamSelect from '@/views/components/ServiceSaleExamSelect'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import ServiceTemSelect from '@/views/components/ServiceTemSelect'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
import { mapMutations, mapState } from 'vuex'
import modelApi from '@/api/modules/system/modelMana'
import lodash from 'lodash'
export default {
  name: 'EditServicePage',
  components: {
    needToLearnSelect,
    ServiceBelongSelect,
    ServiceSaleCateSelect,
    ServiceSaleExamSelect,
    ServiceTemSelect,
    CustomTextArea,
    CarModelCodeSelect
  },
  computed: {
    serviceTemObj () {
      return this.$store.getters.serviceTemObj()
    },
    ...mapState({
      newServiceData: (state) => state.serviceConfig.newServiceData,
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      serviceSaleCateFlagDictCode: (state) => state.dict.serviceSaleCateFlagDictCode,
      serviceSaleBelongFlagDictCode: (state) => state.dict.serviceSaleBelongFlagDictCode,
      serviceSaleExamCodeDictCode: (state) => state.dict.serviceSaleExamCodeDictCode,
    })
  },
  mounted () {
    this.newServiceData.needStudy = 0
  },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    isBack: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      rules: {
        serviceCode: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(this.$t('pleaseInput')))
                return
              }
              if (!/^[0-9A-Z]{1,20}$/.test(value) || !/[A-Z]{1,}/.test(value)) {
                callback(new Error('请输入大写英文字母(可含数字)，不超过20字符'))
                return
              }
              callback()
            }
          }
        ],
        serviceName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(this.$t('pleaseInput')))
                return
              }
              if (!/^[\w\u4e00-\u9fa5_a-zA-Z0-9]{1,20}$/.test(value)) {
                callback(new Error('请输入中英文、数字及下划线，不超过20字符'))
                return
              }
              callback()
            }
          }
        ],
        modelDtoList: [{ required: true, message: this.$t('pleaseSelect'), trigger: 'blur' }],
        serviceBelong: [{ required: true, message: this.$t('pleaseSelect') }],
        serviceCategory: [{ required: true, message: this.$t('pleaseSelect') }],
        serviceExplain: [{ min: 0, max: 200, message: this.$t('length200'), trigger: 'change' }],
        serviceDesc: [{ min: 0, max: 200, message: this.$t('length200'), trigger: 'change' }],
        needStudy: [{ required: true, message: this.$t('pleaseSelect'), trigger: 'change' }],
        examUrl: [{ required: true, message: this.$t('pleaseSelect'), trigger: 'change' }],
        studyUrls: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.newServiceData.studyUrls[0].length) {
                callback(new Error(this.$t('请输入学习地址url')))
                return
              }
              callback()
            }
          }
        ],
      },
      studyUrlErr: [],
      modelOptions: [],
      disabledModelArr: [],
    }
  },
  methods: {
    ...mapMutations(['SET_NEWSERVICE_DATA', 'SET_ServieceRightDrawerEvent']),
    getModelCodeList: lodash.debounce(function(value = '') {
      modelApi.getMyAllModelCode({ searchWord: value, pageSize: 100000 }).then((res) => {
        let data = res.data
        if (!data) {
          return
        }
        data = data.map(item => {
          let showName = item.code
          showName += (item.name ? '[' + item.name + ']' : '')
          // 加code与trimLevel是为了有些地方选择的时候需要这两个参数
          return {
            id: item.code,
            ...item,
            showName,
            code: item.code,
            title: item.name
          }
        })
        this.modelOptions = data
      })
    }, 500),
    searchModelList (input, option) {
      // this.$nextTick( ()=> {
        return (option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0)
      // })
    },
    changeoption (event, key) {
      this.getModelCodeList()
      const vm = this
      vm.$set(vm.newServiceData, key, event)
      vm.$nextTick(() => {
        vm.$refs.formComp.validateField(key)
      })
    },
    initDataForm () {
      this.getModelCodeList()
      const vm = this
      vm.$refs.formComp && vm.$refs.formComp.resetFields()
      if (!vm.isBack) {
        vm.SET_NEWSERVICE_DATA({})
        if (vm.recordData.id) {
          //   编辑
          vm.getServiceConfigInfor()
        }
      } else {
        //由于该方法执行时 serviceSaleExamCodeDictCode未赋值，采用监听的方式判断其是否含有某个对象
      }
      // vm.isgetnull('serviceCategory')
      // vm.isgetnull('serviceBelong')
      // vm.isgetnull('serviceSaleExam')
    },
    // 获取服务详情
    getServiceConfigInfor () {
      const vm = this
      vm.$api.getServiceConfigInfor({ id: this.recordData.id }).then((response) => {
        let tempModelDtoList = response.data.modelDtoList
        delete response.data.modelDtoList
        vm.SET_NEWSERVICE_DATA(response.data)
        vm.newServiceData.studyUrls = response.data.studyUrls && JSON.parse(response.data.studyUrls)
        this.$nextTick(() => {
          if (!! tempModelDtoList) {
            this.disabledModelArr = []
            let tempArr = tempModelDtoList.map(e => e.id)
            this.changeoption(tempArr, 'modelDtoList')
            tempModelDtoList.forEach(e => {
              if (!e.allowDel) {
                this.disabledModelArr.push(e.id)
              }
            })
          }
        })
      })
    },
    // 判断选择的服务归属域或者服务分类是否被删除，如果被删除需要置空选择
    isgetnull (type) {
      const vm = this
      const objDictCode = {
        'serviceCategory': 'serviceSaleCateFlagDictCode',
        'serviceBelong': 'serviceSaleBelongFlagDictCode',
        'serviceSaleExam': 'serviceSaleExamCodeDictCode'
      }
      const includesItem = vm[objDictCode[type]].filter(item => item.value === vm.newServiceData[type])
      if (!includesItem.length) {
        vm.newServiceData[type] = undefined
      }
    },
    addStudyUrls () {
      const vm = this
      let fag = true
      vm.newServiceData.studyUrls.forEach((element, index) => {
        if (!element) {
          fag = false
          vm.$set(vm.studyUrlErr, index, { error: true })
        } else {
          vm.$set(vm.studyUrlErr, index, { error: false })
        }
      })
      if (fag) {
        vm.newServiceData.studyUrls.push('')
      }
    },
    checkStudy (index) {
      const str = this.newServiceData.studyUrls[index]
      if (!str || str.length > 200) {
        this.studyUrlErr[index] = { error: true }
      } else {
        this.studyUrlErr[index] = { error: false }
      }
    },
    getFormData () {
      const vm = this
      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate((valid) => {
          if (!valid) {
            reject(valid)
            return
          }
          const studyUrls = []
          // 判断是否有空字符串
          vm.newServiceData.studyUrls.forEach((item, index) => {
            if (item) {
              studyUrls.push(item)
            } else {
              // 有空字符串
              vm.$set(vm.studyUrlErr, index, { error: true })
            }
          })
          const errArray = this.studyUrlErr.filter(item => item.error)
          if (vm.newServiceData.needStudy && errArray.length) {
            return
          }
          let resultP = {}
          if (vm.newServiceData.id) {
            resultP = {
              id: vm.newServiceData.id,
              serviceCode: vm.newServiceData.serviceCode,
              serviceBelong: vm.newServiceData.serviceBelong,
              serviceCategory: vm.newServiceData.serviceCategory,
              serviceExplain: vm.newServiceData.serviceExplain,
              serviceDesc: vm.newServiceData.serviceDesc,
              needStudy: vm.newServiceData.needStudy,
              examUrl: vm.newServiceData.examUrl,
              modelDtoList: vm.newServiceData.modelDtoList,
              apiStr: 'editServiceConfig',
              serviceName: vm.newServiceData.serviceName, // vm.serviceTemObj[vm.newServiceData.serviceCode]
              studyUrls
            }
          } else {
            resultP = Object.assign(vm.newServiceData, { apiStr: 'addServiceConfig' })
          }
          resolve(resultP)
        })
      })
    },
    // 编辑服务归属域和分类
    editBelogCate (tag) {
      this.SET_ServieceRightDrawerEvent(tag)
    }
  },
  watch: {
    serviceSaleExamCodeDictCode: {
      handler(newV){
        console.log(this.serviceSaleExamCodeDictCode.find(e => e.name == this.newServiceData.examUrl))
        if (this.serviceSaleExamCodeDictCode.find(e => e.name == this.newServiceData.examUrl) == undefined) {
            this.newServiceData.examUrl = ''
          }
        // }
      },
      deep: true
    },
    instantUpdateTime: {
      handler () {
        this.initDataForm()
      },
      immediate: true
    },
    serviceSaleBelongFlagDictCode: {
      handler (val) {
        if(val.length>0){
          this.isgetnull('serviceBelong')
        }
      },
      immediate: true,
      deep:true
    },
    serviceSaleCateFlagDictCode: {
      handler (val) {
        if(val.length>0){
          this.isgetnull('serviceCategory')
        }
      },
      deep:true
    },
  }
}
</script>
<style lang="less" scoped>
.urlItems {
  position: relative;
  margin-bottom: 12px;
  .deleteUlr {
    position: absolute;
    top: 0;
    right: -34px;
    cursor: pointer;
    font-size: 24px;
  }
  .has-error {
    position: absolute;
    bottom: -26px;
    left: 0;
    .ant-form-explain {
      font-size: 1.2rem;
    }
  }
}

.newBtn {
  min-width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #fafafa;
  margin-top: 16px;
  padding: 0;
  font-size: 24px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
